package com.itheima.travel.interceptors;

import com.alibaba.fastjson.JSONObject;
import com.itheima.travel.enums.StatusEnum;
import com.itheima.travel.res.ResponseWrap;
import com.itheima.travel.utils.EmptyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
/*
* 自定义登录拦截器实现HandlerInterceptor接口拦截
* 注入HttpSession对象
* 注入是否为测试环境，测试环境直接放行
*非测试环境判断是否登录，session.getAttribute(session.getId());
* 若登录则放行
* 若未登录将StatusEnum中的未登录状态封装进ResponseWrap转换成json字符串响应给前端页面
* */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    HttpSession session;

    @Value("${context.test}")
    String isTest;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (Boolean.valueOf(isTest)){
            return true;
        }
        boolean isLogin=false;
        Object obj = session.getAttribute(session.getId());
        if (!EmptyUtil.isNullOrEmpty(obj)){
            isLogin=true;
        }
        if (!isLogin){
            //处理响应乱码
            response.setContentType("text/html;charset=utf-8");
            ResponseWrap<String> responseWrap=ResponseWrap.<String>builder()
                    .code(StatusEnum.NO_LOGIN.getCode())
                    .msg(StatusEnum.NO_LOGIN.getMsg())
                    .operationTime(new Date())
                    .data(null)
                    .build();
            //转换json,responseWrap中已处理时间格式
            response.getWriter().write(JSONObject.toJSONString(responseWrap));
            return false;
        }

        return true;
    }
}
